<template>
  <div
    class="main-content"
    ref="containerRef"
    @contextmenu="handleEmptyAreaContextMenu"
    @mousedown="handleMouseDown"
    @mousemove="handleMouseMove"
    @mouseup="handleMouseUp"
  >
    <!-- 框选区域 -->
    <div
      v-if="isSelecting"
      class="selection-box"
      :style="{
        left: selectionBox.left + 'px',
        top: selectionBox.top + 'px',
        width: selectionBox.width + 'px',
        height: selectionBox.height + 'px',
      }"
    ></div>

    <!-- 空目录提示 -->
    <div v-if="fileStore.currentItems.length === 0" class="empty-folder">
      <el-icon size="80" class="empty-icon">
        <FolderOpened />
      </el-icon>
      <p class="empty-title">此文件夹为空</p>
      <p class="empty-subtitle">您可以拖放文件到此处，或右键创建新文件夹</p>
    </div>

    <!-- 文件列表 -->
    <div
      v-else
      class="file-container"
      @contextmenu="handleEmptyAreaContextMenu"
    >
      <!-- 列表模式 -->
      <VirtualFileListV2
        v-if="fileStore.viewMode === 'list'"
        :items="fileStore.currentItems"
        :container-height="containerHeight"
      />

      <!-- 网格模式 -->
      <div
        v-else
        class="file-grid-container"
        :style="{ height: containerHeight - 24 + 'px' }"
      >
        <div class="file-grid">
          <FileItem
            v-for="item in fileStore.currentItems"
            :key="`${item.type}-${item.name}`"
            :item="item"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { FolderOpened } from "@element-plus/icons-vue";
import { useFileStore } from "../stores/fileStore";
import VirtualFileListV2 from "./VirtualFileListV2.vue";
import FileItem from "./FileItem.vue";

const fileStore = useFileStore();

// 容器高度管理
const containerRef = ref<HTMLElement>();
const containerHeight = ref(600);

// 框选多选状态
const isSelecting = ref(false);
const selectionStart = ref({ x: 0, y: 0 });
const selectionEnd = ref({ x: 0, y: 0 });
const selectionBox = computed(() => {
  const left = Math.min(selectionStart.value.x, selectionEnd.value.x);
  const top = Math.min(selectionStart.value.y, selectionEnd.value.y);
  const width = Math.abs(selectionEnd.value.x - selectionStart.value.x);
  const height = Math.abs(selectionEnd.value.y - selectionStart.value.y);
  return { left, top, width, height };
});

// 框选事件处理
const handleMouseDown = (event: MouseEvent) => {
  // 只在空白区域开始框选
  const target = event.target as HTMLElement;

  if (isEmptyAreaTarget(target) && event.button === 0) {
    // 左键点击空白区域
    isSelecting.value = true;
    const rect = containerRef.value!.getBoundingClientRect();
    selectionStart.value = {
      x: event.clientX - rect.left,
      y: event.clientY - rect.top,
    };
    selectionEnd.value = { ...selectionStart.value };

    // 清除当前选中（点击空白区域取消选中）
    fileStore.clearSelection();

    event.preventDefault();
  }
};

const handleMouseMove = (event: MouseEvent) => {
  if (isSelecting.value && containerRef.value) {
    const rect = containerRef.value.getBoundingClientRect();
    selectionEnd.value = {
      x: event.clientX - rect.left,
      y: event.clientY - rect.top,
    };

    // TODO: 计算与框选区域相交的文件项
    event.preventDefault();
  }
};

const handleMouseUp = (event: MouseEvent) => {
  if (isSelecting.value) {
    isSelecting.value = false;
    // TODO: 完成框选，设置选中的文件项
    event.preventDefault();
  }
};

// 优化后的空白区域检查，减少重复DOM查询
const isEmptyAreaTarget = (target: HTMLElement): boolean => {
  return (
    target.classList.contains("main-content") ||
    target.classList.contains("file-container") ||
    target.classList.contains("empty-folder") ||
    target.classList.contains("file-grid-container") ||
    target.classList.contains("file-grid")
  );
};

// 空白区域右键菜单处理
const handleEmptyAreaContextMenu = (event: MouseEvent) => {
  const target = event.target as HTMLElement;

  if (isEmptyAreaTarget(target)) {
    event.preventDefault();
    // 清除当前选中项，显示空白区域菜单
    fileStore.selectedItem = null;
    // 触发右键菜单（父组件会处理菜单显示）
    document.dispatchEvent(
      new CustomEvent("empty-area-contextmenu", {
        detail: { x: event.clientX, y: event.clientY },
      })
    );
  }
};

// 更新容器高度
const updateContainerHeight = () => {
  if (containerRef.value) {
    const rect = containerRef.value.getBoundingClientRect();
    containerHeight.value = rect.height;
  }
};

// ResizeObserver for responsive layout
let resizeObserver: ResizeObserver | null = null;

onMounted(() => {
  if (containerRef.value) {
    resizeObserver = new ResizeObserver(updateContainerHeight);
    resizeObserver.observe(containerRef.value);
    updateContainerHeight();
  }
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
});
</script>

<style scoped lang="scss">
// 样式已迁移到 src/styles/explorer.scss
// 这里只保留组件特有的样式覆盖（如果需要）

// 修复双滚动条问题：FileGrid中的main-content不需要自己的滚动条
.main-content {
  overflow: hidden !important; // 覆盖全局样式，让虚拟滚动组件处理滚动
  padding: 0 !important; // 移除padding，让虚拟滚动组件自己控制
}

// 网格模式样式
.file-grid-container {
  overflow-y: auto;
  overflow-x: hidden;
  padding: 12px;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  align-items: start;

  // 响应式网格
  @media (max-width: 768px) {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
  }

  @media (max-width: 480px) {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 8px;
  }
}

.selection-box {
  position: absolute;
  border: 1px dashed #409eff;
  background: rgba(64, 158, 255, 0.1);
  pointer-events: none;
  z-index: 1000;
}
</style>
